import { type Ref, h, ref, reactive, computed, toRaw, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";

import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import editForm from "../form/index.vue";
import { getUser, addUserAccount, updateUserAccount } from "@/api/user";

export function useUser(tableRef: Ref) {
  // ⚙️状态初始化
  const formRef = ref();
  /** 重置密码 */
  // const ruleFormRef = ref();
  /** 是否处于 Loding 状态 */
  const loading = ref(true);
  /** 账号是否启用 */
  const switchLoadMap = ref({});
  /** 多选操作 */
  const selectedNum = ref(0);
  /** 翻页器定义 */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  /** 账号是否启用样式 */
  const switchStyle = computed(() => {
    return {
      "--el-switch-on-color": "#6abe39",
      "--el-switch-off-color": "#e84749"
    };
  });
  /** 重置密码按钮样式 */
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  /** 表格数据 */
  const dataList = ref([]);
  /** 定义表头 */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "userid",
      width: 130
    },
    {
      label: "用户名",
      prop: "username",
      minWidth: 130
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 130
    },
    {
      label: "邮箱",
      prop: "useremail",
      minWidth: 130
    },
    {
      label: "单位名称",
      prop: "unitname",
      minWidth: 130
    },
    {
      label: "课题组名称",
      prop: "rpgname",
      minWidth: 130
    },
    {
      label: "积分",
      prop: "point",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "enable",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.enable}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  /** 搜索用户表单 */
  const userSearch = reactive({
    key: "",
    email: "",
    status: "",
    unitname: "",
    rpgname: ""
  });
  /** 用户搜素结果数据 */
  let userList = reactive([
    {
      key: "",
      email: "",
      status: "",
      unitname: "",
      rpgname: ""
    }
  ]);

  // 💡方法区
  /** 重置表单 */
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /** 搜索用户方法 */
  async function onSearch() {
    loading.value = true;
    getUser(toRaw(userSearch)).then(res => {
      dataList.value = res.result.data;
      pagination.total = res.result.total;
      loading.value = false;
    });
  }
  /** 新增用户方法 */
  function openDialog(title = "新增", row?: FormItemProps) {
    console.log("row", row);
    if (title == "新增") {
      addDialog({
        title: `${title}用户`,
        props: {
          formInline: {
            title,
            username: row?.username ?? "",
            password: row?.password ?? "",
            phone: row?.phone ?? "",
            useremail: row?.useremail ?? "",
            unitname: row?.unitname ?? "",
            rpgname: row?.rpgname ?? "",
            qq: row?.qq ?? "",
            enable: row?.enable ?? true,
            point: row?.point ?? 0
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef }),
        beforeSure: (done, { options }) => {
          const FormRef = formRef.value.getRef();
          const curData = options.props.formInline as FormItemProps;
          function chores() {
            message(`您${title}了用户名称为${curData.username}的这条数据`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
          FormRef.validate(valid => {
            if (valid) {
              // console.log("curData", curData);
              // 实际开发先调用新增接口，再进行下面操作
              addUserAccount(toRaw(curData)).then(res => {
                console.log(res);
                chores();
              });
            }
          });
        }
      });
    }
    if (title == "修改") {
      addDialog({
        title: `${title}用户`,
        props: {
          formInline: {
            title,
            userid: row?.userid ?? "",
            username: row?.username ?? "",
            password: row?.password ?? "",
            phone: row?.phone ?? "",
            useremail: row?.useremail ?? "",
            unitname: row?.unitname ?? "",
            rpgname: row?.rpgname ?? "",
            qq: row?.qq ?? "",
            enable: row?.enable ?? true,
            point: row?.point ?? 0
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef }),
        beforeSure: (done, { options }) => {
          const FormRef = formRef.value.getRef();
          function chores() {
            message(`您${title}了用户名称为:${curData.username}的这条数据`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
          const curData = options.props.formInline as FormItemProps;
          FormRef.validate(valid => {
            if (valid) {
              console.log("curData", curData);
              // 实际开发先调用新增接口，再进行下面操作
              updateUserAccount(toRaw(curData)).then(() => {
                chores();
              });
            }
          });
        }
      });
    }
    if (title == "查看") {
      addDialog({
        title: `${title}用户`,
        props: {
          formInline: {
            title,
            userid: row?.userid ?? "",
            username: row?.username ?? "",
            password: row?.password ?? "",
            phone: row?.phone ?? "",
            useremail: row?.useremail ?? "",
            unitname: row?.unitname ?? "",
            rpgname: row?.rpgname ?? "",
            qq: row?.qq ?? "",
            enable: row?.enable ?? true,
            point: row?.point ?? 0
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef })
      });
    }
  }
  /** 启用/停用用户方法 */
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.enable === false ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      /** 确认操作 */
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        updateUserAccount(toRaw(row)).then(res => {
          console.log(res);
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          let tips = row.enable === true ? "启用" : "停用";
          let name = row.username;
          message(`已修改 ${name} 状态为 ${tips}`, {
            type: "success"
          });
        });
      })
      /** 取消操作 */
      .catch(() => {
        row.enable === true ? (row.enable = false) : (row.enable = true);
        message("操作取消", {
          type: "warning"
        });
      });
  }

  /** 批量删除用户方法
   *当CheckBox选择项发生变化时会触发该事件
   */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "userid")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }
  /** 取消批量删除选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }
  /** 删除单个用户方法 */
  function handleDelete(row) {
    message(`您删除了用户编号为${row.userid}的这条数据`, { type: "success" });
    onSearch();
  }
  /** 修改单个用户方法 */
  function handleUpdate(row) {
    console.log(row);
  }
  /** 翻页器-改变页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    let search = Object.assign({}, userSearch, {
      size: val,
      page: pagination.currentPage
    });
    // loading.value = true;
    getUser(search).then(res => {
      dataList.value = res.result.data;
      loading.value = false;
    });
    console.log(`${val} items per page`);
  }
  /** 翻页器-改变页数 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    let search = Object.assign({}, userSearch, {
      size: pagination.pageSize,
      page: val
    });
    loading.value = true;
    getUser(search).then(res => {
      dataList.value = res.result.data;
      loading.value = false;
    });
    console.log(`current page: ${val}`);
  }

  function handleReset() {
    console.log("重置密码方法");
  }
  // 页面挂载钩子
  onMounted(async () => {
    onSearch();
  });

  return {
    loading,
    pagination,
    dataList,
    buttonClass,
    columns,
    selectedNum,
    userList,
    userSearch,
    resetForm,
    onSearch,
    openDialog,
    handleSelectionChange,
    handleUpdate,
    handleDelete,
    handleReset,
    onSelectionCancel,
    onbatchDel,
    handleSizeChange,
    handleCurrentChange
  };
}
